import { Directive, HostBinding, Input, ElementRef, Renderer2, SimpleChanges, OnChanges, OnDestroy } from '@angular/core';

import { FormComponent } from '../form/form.component';

let tick = 0;

@Directive({
  selector: '[bzValidator]'
})
export class ValidatorDirective<U, B, S> implements OnChanges, OnDestroy {

  @HostBinding('class.text-error') danger = true;
  @Input() bzValidator: boolean;
  key: string;

  constructor(
    private bzForm: FormComponent<U, B, S>,
    private eleRef: ElementRef,
    private renderer: Renderer2
  ) {
    this.key = 'validator_' + (++tick);
  }

  ngOnChanges(changes: SimpleChanges): void {
    if (changes.bzValidator) {
      this.bzForm.setValidator(this.key, changes.bzValidator.currentValue);
      if (changes.bzValidator.currentValue) {
        this.renderer.removeAttribute(this.eleRef.nativeElement, 'hidden');
      } else {
        this.renderer.setAttribute(this.eleRef.nativeElement, 'hidden', 'hidden');
      }
    }
  }

  ngOnDestroy(): void {
    this.bzForm.setValidator(this.key, false);
  }


}
